
import path from "path";
import fs from "fs";

export class FileInfo {
    name: string = '';
    path: string = '';
    offset: number = 0;
    fd: number = 0;
}

/**
 * @en Demonstration writer
 * @zh 演示数据写入器
 */
export class DemonstrationWriter {


    static streams: Map<string, FileInfo> = new Map<string, FileInfo>();

    static open(name: string, filePath: string) {

        const fileInfo = new FileInfo();
        fileInfo.name = name;

        const fileAbsPath = path.join(Editor.Project.path, filePath, name + '.demo');
        fs.open(fileAbsPath, 'r+', (err, fd) => {
            if (err) {
                console.log('Failed to open file: ' + fileAbsPath);
                return;
            }
            fileInfo.fd = fd;
            fileInfo.path = fileAbsPath;
            this.streams.set(name, fileInfo);
            console.log('Opened file: ' + fileAbsPath);
        });
    }

    static writeBuffer(name: string, buffer: Buffer) {
        const fileInfo = this.streams.get(name);
        if (fileInfo) {
            fs.write(fileInfo.fd, buffer, 0, buffer.byteLength, fileInfo?.offset, (err, bytesWritten) => {
                if (err) {
                    console.log('Failed to write to file: ' + fileInfo?.path);
                    return;
                }
                fileInfo.offset += bytesWritten;
            });
        }

    }

    static close(name: string) {
        const fileInfo = this.streams.get(name);
        if (fileInfo) {
            fs.close(fileInfo.fd, (err) => {
                if (err) {
                    console.log('Failed to close file: ' + fileInfo.path);
                    return;
                }
                this.streams.delete(name);
                console.log('Closed file: ' + fileInfo.path);
            });
        }
    }

    static seek(name: string, offset: number) {
        const fileInfo = this.streams.get(name);
        if (fileInfo) {
            fileInfo.offset = offset;
        }
        console.log('Seeked to offset: ' + offset);
    }
}